/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package org.jackysoft.opensymphony.workflow.util;

import java.io.Serializable;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.entity.Variable;
import org.jackysoft.entity.VariableSetting;
import org.jackysoft.entity.WorkflowEntry;
import org.jackysoft.service.VariableService;
import org.jackysoft.service.VariableSettingService;

/**
 * @author Hani Suleiman (hani@formicary.net) 
 * Date: Oct 14, 2003 
 * Time: 11:58:12   PM
 */
public class DefaultVariableResolver implements VariableResolver, Serializable {
	// ~ Static fields/initializers
	// /////////////////////////////////////////////
	private static final Log logger = LogFactory.getLog(DefaultVariableResolver.class);
	private static final long serialVersionUID = -4819078273560683753L;

	
	public Object getVariableFromMaps(String var, Map transientVars,VariableService wvs,VariableSettingService vss) {
		int firstDot = var.indexOf('.');
		WorkflowEntry entry =  (WorkflowEntry) transientVars.get("entry");
		String actualVar = var;

		if (firstDot != -1) {
			actualVar = var.substring(0, firstDot);
		}

		Object o = transientVars.get(actualVar);

		logger.info(String.format("解析变量,环境transientVars[%s:%s]",actualVar,o));
		if(o!=null) return o;
		
		if(o==null && vss!=null){
			
		    String wname = entry.getWorkflowName();
		    VariableSetting vs = vss.get(wname,actualVar);
		    o = vs==null?null:vs.getValue();			
			logger.info(String.format("解析变量,环境VariableSettingService[%s,%s:%s]",wname,actualVar,o));
		   
		}
		
		if(o!=null) return o;
		
		if (o == null && wvs!=null) {

			Variable wv = wvs.get(entry.getId(), actualVar);
	        o=wv==null?null:wv.getValue();
	        logger.info(String.format("解析变量,环境WorkflowVariableService[%s,%s:%s]",entry.getId(),actualVar,o));
        }
		
		if(o==null) throw new IllegalStateException("变量解析错误 ,上下文环境中无法解析需要的变量 : "+var);
		
		return o;
	}

	/**
	 * Parses a string for instances of "${foo}" and returns a string with all
	 * instances replaced with the string value of the foo object
	 * (<b>foo.toString()</b>). If the string being passed in only refers to a
	 * single variable and contains no other characters (for example: ${foo}),
	 * then the actual object is returned instead of converting it to a string.
	 */
	public Object translateVariables(String s, Map transientVars,VariableService vs,VariableSettingService ps) {
		if(s==null) return null;
		String temp = s.trim();

		if (temp.startsWith("${") && temp.endsWith("}")	&& (temp.indexOf('$', 1) == -1)) {
			// the string is just a variable reference, don't convert it to a
			// string
			String var = temp.substring(2, temp.length() - 1);

			return getVariableFromMaps(var, transientVars,vs,ps);
		} else {
			// the string passed in contains multiple variables (or none!) and
			// should be treated as a string
			while (true) {
				int x = s.indexOf("${");
				int y = s.indexOf("}", x);

				if ((x != -1) && (y != -1)) {
					String var = s.substring(x + 2, y);
					String t = null;
					Object o = getVariableFromMaps(var, transientVars,vs,ps);

					if (o != null) {
						t = o.toString();
					}

					if (t != null) {
						s = s.substring(0, x) + t + s.substring(y + 1);
					} else {
						// the variable doesn't exist, so don't display anything
						s = s.substring(0, x) + s.substring(y + 1);
					}
				} else {
					break;
				}
			}

			return s;
		}
	}

	@Override
	public Object translateVariables(String s, Map transientVars,VariableSettingService ps) {
		return translateVariables(s,transientVars,null,ps);
	}
}
